package cn.itcast.user.controller;


import cn.itcast.hmall.dto.common.ThreadLocalUtil;
import cn.itcast.hmall.pojo.user.Address;
import cn.itcast.hmall.pojo.user.User;
import cn.itcast.user.service.AddressService;
import cn.itcast.user.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author oldwine
 * @date 2022/6/22
 * @Version 1.0
 */
@RestController
public class UserController {
    @Autowired
    private AddressService addressService;

    @Autowired
    private UserService userService;

    /**
     * 扣除用户账户余额
     * @param totalfee 扣除费用
     * @param userId 用户id
     * @return 返回结果
     */
    @GetMapping("/user/pay/{userId}/{totalfee}")
    public Boolean payMoney(@PathVariable("totalfee") Long totalfee, @PathVariable("userId") Long userId) {
        User user = userService.getById(userId);
        Long balance = user.getBalance();
        user.setBalance(balance - totalfee);
        return userService.updateById(user);
    }

    /**
     * 根据用户id查询用户信息
     *
     * @param userId 用户id
     * @return 返回用户信息
     */
    @GetMapping("/user/{userId}")
    public User queryUserById(@PathVariable("userId") Long userId) {
        return userService.getById(userId);
    }

    /**
     * 根据地址id查询地址信息
     *
     * @param id 地址id
     * @return
     */
    @GetMapping("/address/{addressId}")
    public Address getAddress(@PathVariable("addressId") Long id) {
        return addressService.getById(id);
    }

    /**
     * 根据用户id查询用户地址信息
     *
     * @return 返回地址列表
     */
    @GetMapping("/address/uid")
    public List<Address> getUserIdAddress() {
        //1.获取当前用户id
        Long userId = ThreadLocalUtil.getUserId();
        LambdaQueryWrapper<Address> wrapper = Wrappers.lambdaQuery(Address.class);
        wrapper.eq(Address::getUserId, userId);
        List<Address> addresses = addressService.list(wrapper);
        return addresses;
    }
}
